package com.work.formaldehyde.activity;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activityadapter.CityManageAdapter;
import com.work.formaldehyde.model.CityManageModel;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CityManageActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private boolean ok = true;

    private ImageView change_img, city_comeback;
    private LinearLayout adds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 0);
        setContentView(R.layout.activity_citymanage);
        city_comeback = findViewById(R.id.city_comeback);
        city_comeback.setOnClickListener(this);
        if (ApiUtils.isNetworkConnected(CityManageActivity.this))
            inti();
    }

    private ArrayList<String> new_list_view;
    private ArrayList<CityManageModel.data> new_list_views;
    private ListView city_manage_list;
    public CityManageAdapter myAdapter;

    /**
     * 初始加载视图
     */
    public void Init() {
        adds = findViewById(R.id.adds);
        adds.setOnClickListener(this);
        city_manage_list = findViewById(R.id.city_manage_list);
        new_list_views = new ArrayList<>();
        new_list_view = new ArrayList<>();
        city_manage_list.setOnItemClickListener(this);
        if (!Url.USER_ID.equals("")) {
            okHttp_postFromParameters();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 初始化加载调用方法
     */
    public void inti() {
        change_img = findViewById(R.id.change_img);
        change_img.setOnClickListener(this);
        Init();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        reint();
    }

    public void reint() {
        if (!Url.USER_ID.equals("") && ApiUtils.isNetworkConnected(CityManageActivity.this)) {
            ApiUtils.windows(CityManageActivity.this, city_comeback, "请稍后..");
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    ApiUtils.closepopup();
                }
            }, 10000);
            okHttp_postFromParameters();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.change_img:
                if (ok) {
                    change_img.setImageResource(R.mipmap.ok);
                    ok = false;
//                    myAdapter.notifyDataSetChanged();
                    myAdapter = new CityManageAdapter(new_list_views, new_list_view,
                            CityManageActivity.this, ok);
                    city_manage_list.setAdapter(myAdapter);
                } else {
                    change_img.setImageResource(R.mipmap.cag);
                    ok = true;
//                    myAdapter.notifyDataSetChanged();
                    myAdapter = new CityManageAdapter(new_list_views, new_list_view,
                            CityManageActivity.this, ok);
                    city_manage_list.setAdapter(myAdapter);
                }
                break;
            case R.id.city_comeback:
                onBackPressed();
                break;
            case R.id.adds:
                if (!Url.USER_ID.equals("")) {
                    Intent tocity = new Intent(CityManageActivity.this, CityCheckActivity.class);
                    startActivity(tocity, ActivityOptions.makeSceneTransitionAnimation(CityManageActivity.this).toBundle());
                } else {
                    Intent is_login = new Intent(CityManageActivity.this, LoginActivity.class);
                    startActivity(is_login, ActivityOptions.makeSceneTransitionAnimation(CityManageActivity.this).toBundle());
                    ApiUtils.SetToast(CityManageActivity.this, "请先登录");
                }
                break;

        }
    }

    private PopupWindow popupWindows;

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (i == (new_list_view.size() - 1)) {
            if (!Url.USER_ID.equals("")) {
                Intent tocity = new Intent(CityManageActivity.this, CityCheckActivity.class);
                startActivity(tocity, ActivityOptions.makeSceneTransitionAnimation(CityManageActivity.this).toBundle());
            } else {
                Intent is_login = new Intent(CityManageActivity.this, LoginActivity.class);
                startActivity(is_login, ActivityOptions.makeSceneTransitionAnimation(CityManageActivity.this).toBundle());
                ApiUtils.SetToast(CityManageActivity.this, "请先登录");
            }
        }
        if (i != (new_list_view.size() - 1) && !ok) {
            windows(CityManageActivity.this, i, new_list_views.get(i).getCity_id());
        }
    }

    public void windows(Context context, final int i, final String city) {
        View popupwindowviews = LayoutInflater.from(context).inflate(
                R.layout.popup_nowlites, null);
        RelativeLayout dangqian = popupwindowviews.findViewById(R.id.dangqian);
        dangqian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                okHttp_postFromParameter(city, 1);
                popupWindows.dismiss();
            }
        });
        RelativeLayout jieshu = popupwindowviews.findViewById(R.id.jieshu);
        jieshu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (new_list_views.get(i).getIs_remind().equals("0")) {
                    okHttp_postFromParameter(city, 0);
                    popupWindows.dismiss();
                } else {
                    ApiUtils.SetToast(CityManageActivity.this, "不能重复设置");
                }
            }
        });
        popupWindows = new PopupWindow(popupwindowviews, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setAnimationStyle(R.style.popwin_anim_style);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
        popupWindows.showAtLocation(city_manage_list, Gravity.BOTTOM, 0, 0);
    }

    //    private void okHttp_postFromParameters() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID)
//                            .build();
//                    Request request = new Request.Builder().url(Url.GETCITYLIST).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gethot1.sendMessage(message);
//                } catch (
//                        Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }).
//                start();
//    }
    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder().get().url(Url.GETCITYLISTS+ Url.USER_ID + "&logintoken=" + Url.LOGIN_TOKEN).build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gethot1.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    private CityManageModel cityManageModel;
    public Handler gethot1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        cityManageModel = gson.fromJson(msg.obj.toString(),
                                CityManageModel.class);
                        if (new_list_views.size() > 0) {
                            new_list_views.clear();
                            new_list_view.clear();
                        }
                        new_list_views.addAll(cityManageModel.getData());
                        if (cityManageModel.data.size() > 0) {
                            for (int i = 0; i < new_list_views.size() + 1; i++) {
                                new_list_view.add("" + i);
                            }
                            adds.setVisibility(View.GONE);
                        }
                        myAdapter = new CityManageAdapter(new_list_views, new_list_view,
                                CityManageActivity.this, ok);
                        city_manage_list.setAdapter(myAdapter);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    private void okHttp_postFromParameter(final String cityid, final int id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody;
                    Request request;
                    if (id == 0) {
                        formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("cityid", cityid).add("logintoken", Url.LOGIN_TOKEN)
                                .build();
                        request = new Request.Builder().url(Url.ADDCITY).post(formBody).build();
                    } else {
                        formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("cityid", cityid).add("logintoken", Url.LOGIN_TOKEN)
                                .build();
                        request = new Request.Builder().url(Url.DELCITYS).post(formBody).build();
                    }
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot1s.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler gethot1s = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        change_img.setImageResource(R.mipmap.cag);
                        ok = true;
                        reint();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}
